<!-- 聊天界面 -->
<template>
	<view class="bd">

		<view class="custom-navbar">
			<text class="title">{{ userLeftMsg.nickname }}</text>

			<navigator class="personBtn" :url="`/pages/userhome/userhome?id=${id}`">
				<uni-icons type="person-filled" size="1.6rem"></uni-icons>
			</navigator>
		</view>
		<!-- 对方资料卡，玩家点击选择是否展示start -->
		<!-- <view class="PersonMsgTop" v-if="ifShowUserMsg" @click="ifShowUserMsg=false">
			<view class="left">
				<image :src="userLeftMsg.avatarurl"></image>
			</view>
			<view class="right">
				<view class="topMsg">
					{{userLeftMsg.nickname}}
				</view>
				<view class="underMsg">
					{{userLeftMsg.hobby}}
				</view>
			</view>
			<view class="btn">
				<uni-icons type="up" size="30"></uni-icons>

			</view>
		</view>
		<view class="NoPersonMsgTop" v-else @click="ifShowUserMsg=true">
			<view class="btn">
				<uni-icons type="down" size="30"></uni-icons>

			</view>
		</view> -->
		<!-- 对方资料卡，玩家点击选择是否展示end -->
		<!-- 上方展示聊天的内容 start-->
		<view class="ChatCtn">

			<scroll-view @scroll="handleScroll" :scroll-top="scrollTopSet" class="scroll-view" scroll-y
				scroll-with-animation>


				<view class="chatMsg" v-for="(item,index) in fetchChatMsgArray" :key="item.id">

					<view class="chatMsgItemTime" v-if='shouldShowTime(index)'>
						{{formatDateTime(item.sendTime)}}
					</view>

					<view :class="item.receiverId==SingleChatMessageDTO.receiverId ? 'chatMsgItemR' : 'chatMsgItemL'">
						<view class="chatMsgItemPic">
							<view class="chatMsgItemPicImg">
								<image class="chatMsgItemPicImgInner"
									:src="item.receiverId==SingleChatMessageDTO.receiverId ?userRightMsg.avatarurl :userLeftMsg.avatarurl"
									@click="gotoUrl(`/pages/userhome/userhome?id=${item.senderId}`)">
								</image>
							</view>
						</view>

						<view
							:class="{ contentChat: true, 'contentChatR': item.receiverId == SingleChatMessageDTO.receiverId }">
							<view
								:class="item.receiverId==SingleChatMessageDTO.receiverId ? 'chatMsgItemContentR' : 'chatMsgItemContentL'">
								<view class="teeext">{{item.messageText}}</view>
							</view>
						</view>
					</view>

				</view>

			</scroll-view>
		</view>
		<!-- 下发发布聊天框及按钮 -->
		<view class="SendChatMsg">
			<!-- <view class="SendChatMsgCtn"> -->
			<view class="MsgCtn">
				<input v-model="SingleChatMessageDTO.messageText" placeholder="说点什么吧..." class="input-btn"
					hold-keyboard />
			</view>
			<view class="MsgBtn" @click="sendMsgToSb">
				<uni-icons type="paperplane-filled" :size="40" class="iconSend"
					:color="SingleChatMessageDTO.messageText !== '' ? 'green' : 'gray'"></uni-icons>
			</view>
		</view>
	</view>
</template>

<script>
	var websocket = null;
	import moment from 'moment';

	import {
		chatSingleList,
		partnerList, //获取对方信息
		getUserInfo, //获取自己信息
		getUserSomeMsg, //获取大致信息用户id
	} from '@/config/api.js'

	import {
		data
	} from 'uview-ui/libs/mixin/mixin';

	import {
		gotoUrl
	} from '../../utils';

	export default {
		computed() {

		},

		mounted() {
			uni.closeSocket({
				success: () => {
					console.info("退出成功")
					// that.getMatchFun()
				},
			})
			this.createWebSocket(); // 创建 WebSocket 连接
		},

		onLoad(options) {
			//跳转到页面，获取该id
			console.log('chat target id:', options.id)
			this.id = options.id
			this.SingleChatMessageDTO.userId = this.$store.state.userInfo.id;
			this.SingleChatMessageDTO.receiverId = options.id
		},

		onShow() {
			this.addMsgOnPage()
			this.getUsersPic() //获取双方的头像
		},

		data() {
			return {
				gotoUrl,

				ifShowUserMsg: false, //默认不展示对方玩家的资料卡


				scrollTopGet: 0,
				scrollTopSet: 0,

				ifSocketOpen: false,



				singleMsg: '',


				id: -1, //聊天的id


				timeRecord: '', //时刻的记录
				//获取到的聊天信息，根据朋友id
				SingleMsg: {

				},
				SingleChatMessageDTO: {
					userId: -1,
					receiverId: -1,
					messageText: '',
					sendTime: '' // "yyyy-MM-dd HH:mm:ss"
				}, //发送的参数
				chatType: 'singlechat', //发送的参数

				socketOpen: false, // WebSocket 连接是否已打开
				socketMsgQueue: [], // WebSocket 待发送的消息队列
				message: '', // 输入框中的文本内容
				messages: [], // 聊天消息列表



				fetchChatMsgArray: [],
				fetchChatMsg: {}, //拉取到的聊天数据 格式
				//{"createTime":"2024-02-04T20:41:19.442175300","deleted":0,"id":17,"messageText":"555","receiverId":7,"sendTime":"2024-02-04T20:41:19","senderId":4}

				userRightMsg: {}, //自己信息
				userLeftMsg: {}, //对方信息

				socketTask: null,
			}
		},
		watch: {

		},
		methods: {
			handleScroll(e) {
				this.scrollTopGet = e.detail.scrollTop
			},

			scrollToBottom() {
				this.scrollTopSet = this.scrollTopGet
				this.$nextTick(() => {
					this.scrollTopSet = 0
				});
			},

			handleNewMsgScroll() {
				uni.createSelectorQuery().in(this).selectAll('.chatMsg').boundingClientRect(data => {
					if (data.length == 0) return

					let lastMsgOffsetBottom = data[data.length - 1].bottom
					uni.createSelectorQuery().in(this).select('.SendChatMsg').boundingClientRect(data => {
						let msgInputOffsetTop = data.top
						console.log('lastMsgOffsetBottom:', lastMsgOffsetBottom,
							'msgInputOffsetTop', msgInputOffsetTop)

						if (lastMsgOffsetBottom - msgInputOffsetTop < 50) {
							this.scrollToBottom()
						}
					}).exec()
				}).exec()
			},

			shouldShowTime(index) {
				// show time if diff > 3 min
				return index == this.fetchChatMsgArray.length - 1 ?
					true :
					Math.abs(
						new Date(this.fetchChatMsgArray[index + 1].sendTime) -
						new Date(this.fetchChatMsgArray[index].sendTime)
					) > 3 * 60 * 1000
			},

			//获取双方头像start
			async getUsersPic() {

				var that = this
				try {
					const resP1 = await getUserSomeMsg(that.SingleChatMessageDTO.receiverId)
					//查询对方
					console.log("对方信息为=》" + resP1)
					that.userLeftMsg = resP1
				} catch (err) {
					console.log(err)
				}

				try {
					const resP2 = await getUserSomeMsg(that.SingleChatMessageDTO.userId)

					// const [res1,res2] = await Promise.all([resP1,resP2])

					console.log("自己信息为=》" + resP2)
					that.userRightMsg = resP2
				} catch (err) {
					console.log(err)
				}

			},
			//获取双方头像end

			getStatusClass() {
				return 'chatMsgItemL'
			},
			isYesterday(dateTime) {
				const yesterday = new Date();
				yesterday.setDate(yesterday.getDate() - 1);
				return (
					yesterday.getFullYear() === dateTime.getFullYear() &&
					yesterday.getMonth() === dateTime.getMonth() &&
					yesterday.getDate() === dateTime.getDate()
				);
			},
			isToday(dateTime) {
				const today = new Date();
				today.setDate(today.getDate());
				return (

					today.getFullYear() === dateTime.getFullYear() &&
					today.getMonth() === dateTime.getMonth() &&
					today.getDate() === dateTime.getDate()
				);
			},
			formatDateTime(dateTimeStr) {
				const now = new Date(); // 获取当前时间
				const dateTime = new Date(dateTimeStr);

				// 计算时间差（毫秒）
				const timeDiff = now.getTime() - dateTime.getTime();
				const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
				const fiveMinutes = 5 * 60 * 1000; // 五分钟的毫秒数




				if (this.isToday(dateTime)) {

					const hour = this.padZero(dateTime.getHours());
					const minute = this.padZero(dateTime.getMinutes());
					return `${hour}:${minute}`;

				}
				//如果是昨天
				if (this.isYesterday(dateTime)) {

					const hour = this.padZero(dateTime.getHours());
					const minute = this.padZero(dateTime.getMinutes());
					return `昨天 ${hour}:${minute}`;

				}
				// 更久远的时间，返回完整日期（年-月-日 时:分）
				const year = dateTime.getFullYear();
				const month = this.padZero(dateTime.getMonth() + 1);
				const date = this.padZero(dateTime.getDate());
				const hour = this.padZero(dateTime.getHours());
				const minute = this.padZero(dateTime.getMinutes());
				return `${year}-${month}-${date} ${hour}:${minute}`;
			},
			padZero(num) {
				return num < 10 ? '0' + num : num;
			},

			async sendMsgToSb() {


				const date = new Date(); // 获取当前时间


				const dateString = moment(date).format('YYYY-MM-DDTHH:mm:ss');


				console.log(dateString); // 输出当前时间的字符串格式，

				this.SingleChatMessageDTO.sendTime = dateString


				await this.sendSocketMessage()

			},
			createWebSocket(id) {
				var that = this

				that.socketTask = uni.connectSocket({


					url: 'ws://' + that.$baseIp + '/wx/chat/' + that.SingleChatMessageDTO.userId,
					success: () => {
						console.log('WebSocket 连接成功');
						that.socketOpen = true;

						// 发送待发送的消息队列中的所有消息
						while (that.socketMsgQueue.length > 0) {
							const msg = that.socketMsgQueue.shift();
							that.sendSocketMessage(msg);
						}
					},
					fail: (err) => {
						console.error('WebSocket 连接失败:', err);
					}
				});


				that.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					that.ifSocketOpen = true
					// 注：只有连接正常打开中 ，才能正常成功发送消息


				})
				that.socketTask.onMessage((res) => {

					console.log("收到服务器内容：", res.data)
					console.log("收到服务器内容JSON：", JSON.parse(res.data))
					const date = new Date(); // 获取当前时间
					that.getUsersPic()
					const dateString = moment(date).format('YYYY-MM-DDTHH:mm:ss');
					console.log(dateString); // 输出当前时间的字符串格式，
					var getMsg = {}
					getMsg.sendTime = dateString
					getMsg.messageText = JSON.parse(res.data).messageText
					getMsg.receiverId = that.SingleChatMessageDTO.userId
					getMsg.userId = that.SingleChatMessageDTO.receiverId
					that.fetchChatMsgArray.unshift(getMsg)

					//this.handleNewMsgScroll()
				});

				uni.onSocketError((err) => {
					console.error('WebSocket 错误:', err);
					uni.closeSocket({
						success: () => {
							console.info("退出成功")
							// that.getMatchFun()
						},
					})

				});
				// 监听 WebSocket 接收到消息的事件
				uni.onSocketMessage((res) => {
					console.log('WebSocket 收到消息:', res);

					//res的数据格式
					//{data: "{"chatType":"singlechat","messageText":"呦西","senderId":7}"}
					that.messages.push(res.data.messageText);

					// that.addMsgOnPage(1)
				});

				// 监听 WebSocket 错误的事件
				uni.onSocketError((err) => {
					console.error('WebSocket 错误:', err);
					that.webSocketClose()
				});
			},

			webSocketClose() {
				uni.websocket.webSocketClose((res) => {
					console.log('WebSocket 关闭', res);
				});
			},

			// 发送 WebSocket 消息
			async sendSocketMessage(msg) {
				var that = this

				if (that.SingleChatMessageDTO.messageText == '') {
					uni.showToast({
						title: '内容不能为空',
						icon: 'none'
					})
				}
				if (this.socketOpen && that.SingleChatMessageDTO.messageText !== '') {



					await uni.sendSocketMessage({
						// data: msg,
						data: JSON.stringify({
							chatType: that.chatType,
							singleChatMessage: that.SingleChatMessageDTO,
						}),
						chatType: that.chatType,
						SingleChatMessageDTO: that.SingleChatMessageDTO,
						success: async (msg) => {
							that.messages.push(that.SingleChatMessageDTO.messageText)
							console.log('WebSocket 发送消息:', msg);

							this.fetchChatMsgArray.unshift(
								JSON.parse(JSON.stringify(this.SingleChatMessageDTO))
							)
							this.SingleChatMessageDTO.messageText = ''

							this.scrollToBottom()
						},
						fail(err) {
							console.log('WebSocket 发送消息失败:', err);
						}
					});
				} else {
					// 如果 WebSocket 连接未打开，则将消息加入待发送的消息队列中
					that.socketMsgQueue.push(msg);
				}
			},


			//聊天界面的展示
			async addMsgOnPage(type) {
				try {
					const res = await chatSingleList(this.SingleChatMessageDTO.receiverId)

					this.fetchChatMsgArray = res.sort((a, b) => new Date(b.sendTime) - new Date(a.sendTime))

				} catch (err) {
					console.error(err)
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.custom-navbar {
		height: 90rpx;
		background-color: rgba(255, 255, 255, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		border-bottom: 2rpx solid rgb(231, 231, 231);
		position: relative;
	}

	.personBtn {
		position: absolute;
		right: 0.5rem;
		top: 50%;
		transform: translateY(-50%);
	}

	.title {
		letter-spacing: 0.1rem;
		/* background: linear-gradient(to right, rgb(242, 247, 255) 0%, rgb(255, 255, 255) 49%, rgb(255, 255, 255) 50%, rgb(255, 250, 248) 100%); */
		color: black;
		/* 设置文本颜色 */
	}

	.NoPersonMsgTop {
		position: relative;
		height: 60rpx;
		margin-bottom: 20rpx;

		.btn {
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 200rpx;
			display: flex;
			justify-content: center;

			box-shadow: 3rpx 6rpx 6rpx 3rpx rgb(212, 212, 212);
		}
	}

	.PersonMsgTop {
		position: relative;
		height: 180rpx;
		width: 80%;
		margin: 20rpx auto;
		display: flex;
		padding: 10rpx;
		box-shadow: 3px 3px 10rpx 1px rgb(212, 212, 212);

		.btn {
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 200rpx;
			display: flex;
			justify-content: center;

			box-shadow: 3rpx 6rpx 6rpx 3rpx rgb(212, 212, 212);
		}

		.left {
			flex: 1;


			padding: 15rpx;

			image {
				width: 100%;
				height: 100%;

			}
		}

		.right {
			flex: 3;


			text-align: center;

			.topMsg {
				margin-top: 25rpx;
				font-size: 1.1rem;
				font-weight: 500;
			}

			.underMsg {
				margin-top: 20rpx;
				font-weight: 200;
			}
		}
	}

	.scroll-view {
		height: 100%;
		transform: scale(-1);
	}

	.chatMsg {
		display: flex;
		flex-flow: column;
		transform: scale(-1);
	}

	.CCtn {
		display: flex;
		flex-direction: row;
	}

	.chatMsgItemPicImgInner {
		display: block;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.chatMsgItemL,
	.chatMsgItemR {
		margin: 20rpx;
		display: flex;
		gap: 20rpx;
	}

	.chatMsgItemL {
		margin-right: 80rpx;
	}

	.chatMsgItemR {
		margin-left: 80rpx;
		flex-direction: row-reverse;
	}

	.chatMsgItemPicImg {
		z-index: 1;
	}


	.chatMsgItemTime {
		background-color: rgba(0, 0, 0, 0.05);
		margin: 0 auto;
		padding: 2rpx 6rpx;
		border-radius: 10rpx;
	}

	.contentChat {
		flex: 1;
		min-width: 0;
		display: flex;
		justify-content: flex-start;

	}

	.contentChatR {
		flex-direction: row-reverse;
	}

	.chatMsgItemContentL,
	.chatMsgItemContentR {
		min-width: 0;
		word-wrap: break-word;
		/* 允许单词内换行 */
		/* 兼容旧版本浏览器 */
		text-align: left;

		.teeext {
			min-width: 0;
			overflow-wrap: break-word;
		}


		padding: 18rpx 20rpx;
		letter-spacing: 0.1rem;
		/* 垂直居中 */
		display: flex;
		height: auto;
		/* 修改这里 */
		align-items: center;
		/* 添加这行 */
		font-size: 1rem;
		border-radius: 20rpx;
		word-break: keep-all;
		/* 中文字符保持在一行上，英文和数字根据需要换行 */
	}

	.chatMsgItemContentL {
		/* background-color: rgb(68, 184, 255); */
		background-color: rgb(255, 255, 255);

	}

	.chatMsgItemContentR {
		// display: inline-block;
		// padding: 10rpx;
		background-color: rgb(208, 211, 226);
		position: relative;
	}

	.chatMsgItemPic {
		z-index: 1;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: flex-start;
		position: relative;
	}


	.input-btn {
		padding: 0 20rpx;
		height: 100%;
	}

	.MsgBtn {
		flex: 1;
		height: 100rpx;
		line-height: 100rpx;
		align-items: center;
		justify-content: center;
		display: flex;
		border-left: solid rgb(241, 241, 241) 2rpx;

		.iconSend {
			margin: auto;
		}
	}

	.MsgCtn {
		flex: 5;
		height: 100rpx;

		background-color: white;
	}

	.ChatCtn {
		box-sizing: border-box;
		flex: 1;
		min-height: 0;
		text-align: center;
	}

	.SendChatMsg {
		box-sizing: border-box;
		display: flex;


		position: sticky;
		bottom: 0;
		width: 80%;
		padding: 5rpx;



		box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
		border: 2rpx solid rgb(241, 241, 241);
		margin: auto;

		background-color: white;

		margin-bottom: 0rpx;

	}

	.bd {
		width: 100%;
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		/* background-color: rgb(241, 241, 241); */
		background: linear-gradient(100deg, #91abd33d 0%, #c2907c21 100%);
	}
</style>